#!/usr/bin/env Rscript
# Copyright (c) 2011-2012, Universite de Versailles St-Quentin-en-Yvelines
#
# This file is part of ASK.  ASK is free software: you can redistribute
# it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# This module bootstrap n points in a random latin square
# configuration.


suppressPackageStartupMessages(require(lhs, quietly=T))

# Parse the arguments
args <- commandArgs(trailingOnly = T)
if (length(args) != 2) {
    stop("Usage: latinsquare <configuration.conf> <output_file>")
}
source(file.path(Sys.getenv("ASKHOME"), "common/configuration.R"))

# Check that n is an integer
if (!is.numeric(conf("modules.bootstrap.params.n"))) {
  stop("modules.bootstrap.params.n must be an integer")
}

seed = conf("modules.bootstrap.params.seed", default="default")
if (seed != "default") {
    set.seed(as.integer(seed))
}

# Generate a latin square configuration for the factors
if (conf("modules.bootstrap.params.method", "random") == "genetic") {
    samples = geneticLHS(as.integer(conf("modules.bootstrap.params.n")),
        length(conf("factors")))
} else 
if (conf("modules.bootstrap.params.method", "random") == "maximin") {
    samples = maximinLHS(as.integer(conf("modules.bootstrap.params.n")),
        length(conf("factors")))
} else 
{
    samples = randomLHS(as.integer(conf("modules.bootstrap.params.n")),
        length(conf("factors")))
}

# Save latinsquare model for possible future augmenting by latinsquare sampler
save(samples, file=file.path(conf("output_directory"), "last_latinsquare.data"))

# Resample columns according to the factor ranges
# and round columns corresponding to integer factors
i = 1
for (f in conf("factors")) {
  if (f$type == "categorical") {
    samples[,i] = length(f$values)*samples[,i]
  }
  else
  {
    samples[,i] = f$range$min + (f$range$max-f$range$min)*samples[,i]
  }

  # Round columns for non float factors
  if (f$type != "float") {
    samples[,i] = as.integer(samples[,i])
  }
  i = i + 1
}

# Write samples to output file
write.table(samples, args[2], sep=" ", quote=F, col.names=F, row.names=F)
